package com.yunmang.activity.setting;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yunmang.R;
import com.yunmang.activity.BaseActivity;
import com.yunmang.activity.kaipiaoActivity;
import com.yunmang.adapter.setting.PrintAdapter;
import com.yunmang.adapter.setting.TagAdapter;
import com.yunmang.utils.SharedPreferencesUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import HPRTAndroidSDK.HPRTPrinterHelper;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/5/4.
 */
public class SettingActivity extends BaseActivity {
    @InjectView(R.id.setPrintBtn)
    TextView setPrintBtn;
    @InjectView(R.id.set_print_listview)
    ListView printListview;
    @InjectView(R.id.print_xiaopiao)
    LinearLayout printXiaopiao;
    @InjectView(R.id.set_tag_listview)
    ListView tagListview;
    @InjectView(R.id.print_biaoqian)
    LinearLayout printBiaoqian;

    public BluetoothAdapter myBluetoothAdapter;
    public String SelectedTagMac = "";
    public String SelectedPrintMac = "";
    public String selectedPrintName="",selectedTagName="";
    private PrintAdapter mprinterAdapter;
    private TagAdapter mTagAdapter;
    private InputStream mmInStream;
    private OutputStream mmOutStream;
    private BluetoothDevice mmDevice;
    private BluetoothSocket mmSocket;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    @Override
    public int getLayoutId() {
        return R.layout.activity_settingprintter;
    }

    @Override
    public void initView() {
        ButterKnife.inject(this);
    }

    @Override
    public void initData() {
        if("".equals(SelectedPrintMac)){
            SelectedPrintMac = SharedPreferencesUtils.getParameter(this, "SelectedPrintMac");
        }else if("".equals(SelectedTagMac)){
            SelectedTagMac = SharedPreferencesUtils.getParameter(this, "SelectedTagMac");
        }
        selectedTagName=SharedPreferencesUtils.getParameter(this, "selectedTagName");
        selectedPrintName=SharedPreferencesUtils.getParameter(this, "selectedPrintName");

        if (!ListBluetoothDevice()){
            finish();
        }
    }

    @OnClick(R.id.setPrintBtn)
    public void confirm(){
        SharedPreferencesUtils.saveParameter(this, "SelectedTagMac",SelectedTagMac);
        SharedPreferencesUtils.saveParameter(this, "SelectedPrintMac",SelectedPrintMac);
        SharedPreferencesUtils.saveParameter(this, "selectedPrintName", selectedPrintName);
        SharedPreferencesUtils.saveParameter(this, "selectedTagName",selectedTagName);
        Log.i("SelectedPrintMac", SharedPreferencesUtils.getParameter(this, "SelectedPrintMac"));
        Log.i("SelectedTagMac", SharedPreferencesUtils.getParameter(this, "SelectedTagMac"));
        if("".equals(SelectedPrintMac)){
            showToast("请选择小票打印机！");
            return;
        }
        if(!TextUtils.isEmpty(SelectedTagMac)&&selectedTagName.equals("HM-T300")){
            new Thread(){
                public void run() {
                        if(!HPRTPrinterHelper.IsOpened()){//如果连接了，就不在连接
                            tryconnect();
                        }
                }
            }.start();
        }
            finish();
    }
    /**
     * 列举出来所有的蓝牙装置
     * @return
     */
    public boolean ListBluetoothDevice() {
        final List<Map<String, String>> list = new ArrayList<>();
        if ((myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()) == null) {
            Toast.makeText(this, "没有找到蓝牙适配器", Toast.LENGTH_LONG).show();
            return false;
        }
        if (!myBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 2);
        }
        Set<BluetoothDevice> pairedDevices = myBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() <= 0){
            return false;
        }
        for (BluetoothDevice device : pairedDevices) {
            Map<String, String> map = new HashMap<>();
            map.put("DeviceName", device.getName());
            map.put("BDAddress", device.getAddress());
            list.add(map);
        }
        mprinterAdapter=new PrintAdapter(this,list);
        mTagAdapter=new TagAdapter(this,list);
        printListview.setAdapter(mprinterAdapter);
        tagListview.setAdapter(mTagAdapter);
        printListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                SelectedPrintMac = list.get(position).get("BDAddress");
                selectedPrintName=list.get(position).get("DeviceName");
                PrintAdapter.changeColor(position);
                mprinterAdapter.notifyDataSetInvalidated();
            }
        });
        tagListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                SelectedTagMac = list.get(position).get("BDAddress");
                selectedTagName=list.get(position).get("DeviceName");
                mTagAdapter.changeColor(position);
                mTagAdapter.notifyDataSetInvalidated();
            }
        });
        return true;
    }


    private void tryconnect() {
        boolean hasConnected=false;
        hasConnected= ConnectDevice();
        if (hasConnected){
            DisConnect();
        }
        if(hasConnected){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showToast("连接成功");
                }
            });
            kaipiaoActivity.HPRTPrinter=new HPRTPrinterHelper(this,"HM-T300");
            try {
                if(HPRTPrinterHelper.PortOpen("Bluetooth,"+SelectedTagMac)==0){
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showToast("连接失败");
                    hideWaitingDialog();
                }
            });
        }
    }

    private boolean ConnectDevice(){
        boolean bRet=false;
        myBluetoothAdapter.cancelDiscovery();
        try
        {
            Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        try
        {
            // 4.0.3版本 经测试，高版本兼容低版本
            mmDevice = myBluetoothAdapter.getRemoteDevice(SelectedTagMac);
            if(Build.VERSION.SDK_INT < 15)
            {
                mmSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
            }
            else
            {
                mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
            }
            myBluetoothAdapter.cancelDiscovery();
            Thread.sleep(100);
            if(myBluetoothAdapter.isDiscovering())
            {
                int iCnt=0;
                while (iCnt<5)
                {
                    Thread.sleep(100);
                    iCnt++;
                    if(myBluetoothAdapter.cancelDiscovery())
                    {
                        break;
                    }
                }
            }
            mmSocket.connect();
        }
        catch (Exception e)
        {
            try
            {
                Method m;
                m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
                mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);
                if(myBluetoothAdapter.isDiscovering())
                {
                    int iCnt=0;
                    while (iCnt<5)
                    {
                        Thread.sleep(100);
                        iCnt++;
                        if(myBluetoothAdapter.cancelDiscovery())
                        {
                            break;
                        }
                    }
                }
                mmSocket.connect();
            }
            catch (Exception e1)
            {
                Log.d("PRTLIB", (new StringBuilder("BTO_ConnectDevice --> create ")).append(e1.getMessage()).toString());
                return false;
            }
        }

        try
        {
            bRet=GetIOInterface();
            return bRet;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    private boolean GetIOInterface(){
        Log.d("PRTLIB", "BTO_GetIOInterface...");
        try
        {
            mmInStream = mmSocket.getInputStream();
            mmOutStream = mmSocket.getOutputStream();
        }
        catch(IOException e)
        {
            Log.d("PRTLIB", (new StringBuilder("BTO_GetIOInterface ")).append(e.getMessage()).toString());
            return false;
        }
        return true;
    }

    private boolean DisConnect(){
        boolean bRet = true;
        try
        {
            Thread.sleep(500);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        try
        {
            if(mmInStream!=null)
            {
                mmInStream.close();
                mmInStream=null;
            }
            if(mmOutStream!=null)
            {
                mmOutStream.close();
                mmOutStream=null;
            }
            if(mmSocket!=null)
            {
                mmSocket.close();
                mmSocket=null;
            }
        }
        catch (IOException e)
        {
            System.out.println((new StringBuilder("BTO_ConnectDevice close ")).append(e.getMessage()).toString());
            bRet = false;
        }
        return bRet;
    }

}
